package com.yiren.backstage.communication.utils;

import android.content.Context;

import com.yiren.backstage.communication.analysis.GyroDataAnalysis;
import com.yiren.backstage.communication.interfaces.DataCallback;
import com.yiren.backstage.communication.interfaces.SimpleCallback;
import com.yiren.backstage.config.api.LoadConfigApi;

import org.apache.commons.lang.StringUtils;

/**
 * Created by WANGRONGXIANG
 * on 2022/4/27
 * Describe
 */
public class ZiyanGyroGearUtil {
    private static Context mContext;
    private OnZiyanDataListener listener;
    private int gear;          //档位

    private float resetX = 0;  //重置差值后的X值
    private float resetY = 0;  //重置差值后的Y值
    private final String SEPARATOR = ":";
    private float[][] xys = new float[6][4];

    private static ZiyanGyroGearUtil ziyanGyroGearUtil = new ZiyanGyroGearUtil();

    public static ZiyanGyroGearUtil getInstance(Context context) {
        mContext = context;
        return ziyanGyroGearUtil;
    }

    public int getGear() {
        return gear;
    }

    public void setZiyanGearData() {
        resetParamValue();
        GyroDataAnalysis.getInstance(mContext).getZiyanData(dataCallback);
    }

    public void getZiyanGearData(OnZiyanDataListener listener) {
        this.listener = listener;
    }

    public void resetParamValue() {
        String reset = LoadConfigApi.loadDeviceStudyConfig(mContext).getXyGearReset();
        if (StringUtils.isNotEmpty(reset)) {
            String[] str = reset.split(":");
            resetX = Float.parseFloat(str[0]);
            resetY = Float.parseFloat(str[1]);
        }
        String data = LoadConfigApi.loadDeviceStudyConfig(mContext).getXyMechanicalGearStudy();
        if (StringUtils.isNotEmpty(data)) {
            xys = ArrayConvertUtil.convertString2Floats(data, 6, 4);
        }
    }

    private SimpleCallback dataCallback = new SimpleCallback() {

        @Override
        public void onReadData(String data) {
            if (listener != null) {
                listener.onZiyanData(data);
            }
            String[] str = data.split(";");
            float x = (360f - Float.parseFloat(str[4])) - resetX;
            float y = (360f - Float.parseFloat(str[5])) - resetY;
            boolean hasGear = false;
            for (int i = 0; i < 6; i++) {
                if (x >= xys[i][0] && x <= xys[i][1] && y >= xys[i][2] && y <= xys[i][3]) {
                    hasGear = true;
                    gear = i + 1;
                }
            }
            if (!hasGear) {
                gear = 0;
            }
        }
    };

    public interface OnZiyanDataListener {
        void onZiyanData(String data);
    }

}
